import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import CheckBox from './index';
import { cloneDeep } from 'loadsh';

function CheckBoxGroup(props) {
  // disabled 整组失效
  const { options, disabled, onChange, defaultValue } = props;

  const [value, setValue] = useState(defaultValue || []);

  // 默认值
  const getCheckboxGroupOptionList = () => {
    let cr = [];
    // options 得值有两种状态 数组 [1, 2, 3]
    //                       对象 [{label: 'xxx', value: 'xxx',check: 'xxx'}]
    if (options && options instanceof Array) {
      // 将options中的每一项处理成符合checkbox规范的props  {check，disabled，children，onChange}
      options.map((v) => {
        let optionItem = {};
        if (typeof v === 'object') {
          // 判断当前的选项 是否被设置了默认选中
          defaultValue.includes(v.value) && (v.check = true);
          optionItem = { ...v };
        }

        if (typeof v === 'string' || typeof v === 'number') {
          optionItem['value'] = v;
          defaultValue.includes(v) && (optionItem.check = true);
        }
        optionItem['disabled'] = disabled;
        cr.push(optionItem);
      });
    }

    return cr;
  };

  // 当点击item发生改变
  const change = (v) => {
    let cloneValue = cloneDeep(value);
    let key = cloneValue.indexOf(v.value);
    if (key === -1) {
      cloneValue.push(v.value);
    } else {
      cloneValue.splice(key, 1);
    }

    setValue(cloneValue);
    onChange(cloneValue);
  };

  return (
    <div>
      {getCheckboxGroupOptionList().map((v) => {
        return <CheckBox {...v} onChange={change} />;
      })}
    </div>
  );
}

// options, disabled, onChange, defaultValue

// 类型检查
CheckBoxGroup.propTypes = {
  options: PropTypes.array,
  disabled: PropTypes.bool,
  onChange: PropTypes.func.isRequired,
  defaultValue: PropTypes.array,
};

// 入参默认值
CheckBoxGroup.defaultProps = {
  checked: false,
  disabled: false,
  defaultValue: [],
};

export default CheckBoxGroup;
